package com.whj.wkpt.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.whj.wkpt.config.AlipayTemplate;
import com.whj.wkpt.entity.Task;
import com.whj.wkpt.entity.TaskApplication;
import com.whj.wkpt.service.TaskApplicationService;
import com.whj.wkpt.service.TaskService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付宝支付接口
 */
@Controller
@RequestMapping("/alipay")
public class AliPayController {

    @Autowired
    AlipayTemplate alipayTemplate;
    
    @Autowired
    TaskService taskService;
    
    @Autowired
    TaskApplicationService taskApplicationService;

    /**
     * 发起支付请求
     * @param taskId 任务ID
     * @return 支付页面HTML
     * @throws AlipayApiException
     */
    @GetMapping(value = "/pay", produces = "text/html;charset=utf-8")
    public void pay(@RequestParam Long taskId, 
                    @RequestParam(required = false) Long applicationId,
                    HttpServletResponse response) throws Exception {
        // 获取任务信息
        Task task = taskService.findById(taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        // 检查任务状态是否为confirmed（已确认交付）
        TaskApplication application = null;
        if (applicationId != null) {
            // 如果提供了applicationId，检查该任务承接是否为confirmed状态
            application = taskApplicationService.findById(applicationId);
            if (application == null || !"confirmed".equals(application.getDeliveryStatus())) {
                throw new RuntimeException("任务承接状态不正确，无法支付");
            }
        } else {
            // 如果没有提供applicationId，检查任务是否为confirmed状态（向后兼容）
            if (!"confirmed".equals(task.getTaskStatus())) {
                throw new RuntimeException("任务状态不正确，无法支付");
            }
        }
        
        // 调用支付宝支付模板发起支付
        String form = alipayTemplate.pay(task);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }
    
    /**
     * 支付宝异步通知接口
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            
            // 支付宝验签
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params, alipayTemplate.alipayPublicKey, alipayTemplate.getCharset(), alipayTemplate.getSignType());
            
            System.out.println("支付宝验签结果: " + signVerified);
            
            if (signVerified) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                
                // 更新订单状态
                Long taskId = Long.valueOf(params.get("out_trade_no"));
                Task task = taskService.findById(taskId);
                if (task != null) {
                    task.setTaskStatus("completed");
                    task.setUpdateTime(LocalDateTime.now());
                    taskService.updateTask(task);
                    System.out.println("任务状态已更新为已完成: " + taskId);
                    
                    // 同时更新相关的任务承接状态为已完成
                    List<TaskApplication> applications = taskApplicationService.findByTaskId(taskId);
                    for (TaskApplication application : applications) {
                        if ("confirmed".equals(application.getDeliveryStatus())) {
                            application.setDeliveryStatus("completed");
                            taskApplicationService.updateApplication(application);
                            System.out.println("任务承接状态已更新为已完成: " + application.getApplicationId());
                        }
                    }
                }
            }
        }
        return "success";
    }
    
    /**
     * 支付宝同步返回接口
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/return")
    public String payReturn(HttpServletRequest request) throws Exception {
        System.out.println("=========支付宝同步回调========");
        
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        
        // 验签
        boolean signVerified = AlipaySignature.rsaCheckV1(
                params, alipayTemplate.alipayPublicKey, alipayTemplate.getCharset(), alipayTemplate.getSignType());
        
        System.out.println("支付宝同步回调验签结果: " + signVerified);
        
        if (signVerified) {
            System.out.println("交易状态: " + params.get("trade_status"));
            System.out.println("商户订单号: " + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            
            // 更新订单状态
            Long taskId = Long.valueOf(params.get("out_trade_no"));
            Task task = taskService.findById(taskId);
            if (task != null) {
                task.setTaskStatus("completed");
                task.setUpdateTime(LocalDateTime.now());
                taskService.updateTask(task);
                System.out.println("任务状态已更新为已完成: " + taskId);
                
                // 同时更新相关的任务承接状态为已完成
                List<TaskApplication> applications = taskApplicationService.findByTaskId(taskId);
                for (TaskApplication application : applications) {
                    if ("confirmed".equals(application.getDeliveryStatus())) {
                        application.setDeliveryStatus("completed");
                        taskApplicationService.updateApplication(application);
                        System.out.println("任务承接状态已更新为已完成: " + application.getApplicationId());
                    }
                }
            }
            
            // 可以在这里添加支付成功的页面跳转逻辑
            return "redirect:/employer/task-applications";
        } else {
            // 验签失败
            return "redirect:/employer/task-applications";
        }
    }
}